<template>
  <div class="space-member-container">
    <h1 class="page-title">空间成员管理</h1>

    <div class="add-member-section">
      <el-input
          v-model.number="newUserId"
          placeholder="请输入用户 id"
          class="user-id-input"
      />
      <el-button type="primary" @click="AddMember" class="custom-button">添加用户</el-button>
    </div>

    <el-table :data="members" class="member-table">
      <el-table-column label="用户" min-width="250">
        <template #default="{ row }">
          <div class="user-cell">
            <el-avatar
                :src="row.avatar"
                :size="32"
            />
            <span class="user-name">{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="角色" width="250">
        <template #default="{ row }">
          <el-select v-model="row.role" class="role-select" :disabled="row.id === currentUserId" @change="onRoleChange(row)">
            <el-option v-if="row.id === currentUserId" label="管理员" value="admin" />
            <el-option label="编辑者" value="editor" />
            <el-option label="浏览者" value="viewer" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="200">
        <template #default="{ row }">
          {{ row.createTime }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button
              type="danger"
              link
              @click="deleteMemberAction(row)"
              :disabled="row.id === currentUserId"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addMember, deleteMember, listMembers, updateMemberRole } from '@/api/form'

// 首先定义 props
const props = defineProps({
  spaceId: {
    type: [String, Number],
    required: true
  }
})

// 然后再初始化 spaceId
const spaceId = ref(props.spaceId)

const newUserId = ref(null)
const members = ref([])

// 从 localStorage 获取当前用户的 userId
const currentUserInfo = JSON.parse(localStorage.getItem('userInfo'))
const currentUserId = currentUserInfo ? currentUserInfo.userId : null

// 其他逻辑保持不变
const fetchMembers = async () => {
  try {
    const response = await listMembers(spaceId.value)
    if (response.code === 1) {
      members.value = response.data.map(member => ({
        id: member.userId,
        name: member.nickName,
        role: member.formRole,
        avatar: member.avatar || 'https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-io5EYmQQIw8CckvW2vCLeCUADF8R5T.png',
        createTime: member.createTime
      }))
    } else {
      ElMessage.error('获取成员列表失败: ' + response.data.msg)
    }
  } catch (error) {
    ElMessage.error('获取成员列表失败: ' + error.message)
  }
}

const AddMember = async () => {
  if (!newUserId.value) {
    ElMessage.warning('请输入用户ID');
    return;
  }
  try {
    const response = await addMember(spaceId.value, newUserId.value);

    if (response.code === 1) {
      // 根据接口返回的数据格式修改这里
      members.value.push({
        id: newUserId.value, // 添加成功后，假设你可以从 newUserId 获取新成员的 ID
        name: response.data.nickName,
        role: 'viewer', // 默认角色
        avatar: response.data.avatar, // 默认头像，或根据实际需求填写
        createTime: new Date().toLocaleString() // 创建时间
      });

      newUserId.value = null; // 或者 newUserId.value = 0
      ElMessage.success('添加成功');
    } else {
      ElMessage.error('添加失败: ' + response.msg); // 这里应该使用 response.msg
    }
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message);
  }
}



const deleteMemberAction = async (member) => {
  if (member.id === currentUserId) {
    ElMessage.warning('不能删除自己')
    return
  }

  // 弹出确认对话框
  ElMessageBox.confirm(
      `确定要删除用户 ${member.name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const response = await deleteMember(spaceId.value, member.id)
      if (response.code === 1) {  // 假设后端返回的数据中有一个 success 字段
        members.value = members.value.filter(m => m.id !== member.id)
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败: ' + response.msg)
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户点击了取消按钮
    ElMessage.info('已取消删除')
  })
}

const onRoleChange = async (row) => {
  if (row.id !== currentUserId) {
    try {
      const response = await updateMemberRole(spaceId.value, row.id, row.role)
      if (response.code === 1) {  // 假设后端返回的数据中有一个 success 字段
        ElMessage.success('角色更新成功')
      } else {
        ElMessage.error('角色更新失败: ' + response.msg)
        row.role = row.originalRole  // 恢复原始角色
      }
    } catch (error) {
      ElMessage.error('角色更新失败: ' + error.message)
      row.role = row.originalRole  // 恢复原始角色
    }
  }
}

onMounted(() => {
  fetchMembers()  // 在组件挂载时获取成员列表
})

// 监听 spaceId 变化，重新获取成员列表
watch(
    () => props.spaceId,
    (newSpaceId) => {
      if (newSpaceId) {
        spaceId.value = newSpaceId;
        fetchMembers();
      }
    },
    { immediate: true }  // 让它在组件加载时也执行一次
);
</script>

<style scoped>
.space-member-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 24px;
}

.add-member-section {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.user-id-input {
  width: 240px;
}

.member-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  color: #374151;
  font-weight: 500;
}

.role-select {
  width: 120px;
}

:deep(.el-table) {
  --el-table-border-color: #f3f4f6;
  --el-table-header-bg-color: #f9fafb;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #374151;
}

:deep(.el-button--danger) {
  color: #dc2626;
}

.custom-button {
  background-color: #00b38a;
  border-color: #00b38a;
}
</style>
